// FundDB.ts
export interface FundItem {
  // 基础信息
  code: string // 基金代码（必填）
  fullCode: string // 完整基金代码（必填）
  name?: string // 基金名称（可选）
  platform?: string // 基金所属平台（可选，如支付宝、天天基金、银行等）
  // 价格相关
  price?: number | string // 最新净值（可选）
  preClose?: number | string // 昨日净值（可选）
  change?: number | string // 涨跌幅（可选）
  // 持仓相关
  cost?: number // 成本价（可选）
  holdings?: number // 持仓数量（可选）
  fee?: number // 手续费（可选）
  // 新增计算字段
  profit?: string | number // 总盈亏
  todayProfit?: string | number // 今日盈亏
  investment?: string | number // 投入金额
  holdingValue?: string | number // 持仓金额（持仓数量 × 当前净值）
  // 基金特有字段
  fundType?: string // 基金类型（如股票型、债券型等）
  navDate?: string // 净值日期
  // 保留扩展能力
  [key: string]: any // 允许其他属性
}

// 打开数据库并创建存储对象
const openDB = (): Promise<IDBDatabase> => {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open('FundDB', 1)

    request.onupgradeneeded = (event) => {
      const db = (event.target as IDBOpenDBRequest).result
      if (!db.objectStoreNames.contains('funds')) {
        // 创建存储对象，以code作为主键
        db.createObjectStore('funds', { keyPath: 'code' })
      }
    }

    request.onsuccess = (event) => {
      resolve((event.target as IDBOpenDBRequest).result)
    }

    request.onerror = (event) => {
      console.error('打开基金数据库失败:', (event.target as IDBOpenDBRequest).error)
      reject((event.target as IDBOpenDBRequest).error)
    }
  })
}

// 获取所有基金数据
export const getAllFunds = async (): Promise<FundItem[]> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('funds', 'readonly')
    const store = transaction.objectStore('funds')
    const request = store.getAll()

    request.onsuccess = () => {
      resolve(request.result)
    }

    request.onerror = () => {
      console.error('获取基金数据失败:', request.error)
      reject(request.error)
    }
  })
}

// 根据代码获取基金
export const getFundByCode = async (code: string): Promise<FundItem | null> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('funds', 'readonly')
    const store = transaction.objectStore('funds')
    const request = store.get(code)

    request.onsuccess = () => {
      resolve(request.result)
    }

    request.onerror = () => {
      console.error(`获取基金 ${code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 添加新基金
export const addFund = async (fund: FundItem): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('funds', 'readwrite')
    const store = transaction.objectStore('funds')
    const request = store.add(fund)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`添加基金 ${fund.code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 更新基金
export const updateFund = async (fund: FundItem): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('funds', 'readwrite')
    const store = transaction.objectStore('funds')
    const request = store.put(fund)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`更新基金 ${fund.code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 批量更新基金
export const batchUpdateFunds = async (funds: FundItem[]): Promise<void> => {
  if (funds.length === 0) {
    return Promise.resolve()
  }

  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('funds', 'readwrite')
    const store = transaction.objectStore('funds')

    // 批量添加所有基金更新操作
    funds.forEach((fund) => {
      store.put(fund)
    })

    // 事务完成时处理
    transaction.oncomplete = () => {
      console.log(`成功批量更新 ${funds.length} 条基金数据`)
      resolve()
    }

    // 事务出错时处理
    transaction.onerror = () => {
      console.error('批量更新基金失败:', transaction.error)
      reject(transaction.error)
    }
  })
}

// 删除基金
export const deleteFund = async (code: string): Promise<void> => {
  const db = await openDB()
  return new Promise((resolve, reject) => {
    const transaction = db.transaction('funds', 'readwrite')
    const store = transaction.objectStore('funds')
    const request = store.delete(code)

    request.onsuccess = () => {
      resolve()
    }

    request.onerror = () => {
      console.error(`删除基金 ${code} 失败:`, request.error)
      reject(request.error)
    }
  })
}

// 初始化数据库（如果为空则导入初始数据）
export const initDB = async (initialData: FundItem[]): Promise<void> => {
  const funds = await getAllFunds()
  if (funds.length === 0) {
    const db = await openDB()
    return new Promise((resolve, reject) => {
      const transaction = db.transaction('funds', 'readwrite')
      const store = transaction.objectStore('funds')

      initialData.forEach((fund) => {
        store.add(fund)
      })

      transaction.oncomplete = () => {
        resolve()
      }

      transaction.onerror = () => {
        console.error('初始化基金数据库失败:', transaction.error)
        reject(transaction.error)
      }
    })
  }
}
